package br.ufrn.streamap.model.dao;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.NoResultException;
import javax.persistence.Persistence;


public abstract class GenericHibernateDAO<T, ID extends Serializable> implements GenericDAO<T, ID> {
	
	public static final String ENVIRONMENT_TEST = "Test";
	public static final String ENVIRONMENT_DEVELOPMENT = "Development";
	public static final String ENVIRONMENT_PRODUCTION = "Production";
	
	
	protected static final EntityManagerFactory factory = Persistence.createEntityManagerFactory(ENVIRONMENT_TEST);
	
	
	
	EntityManager em = null;

	
	public GenericHibernateDAO() {
		
	}
	
	
	@Override
	public T save(T entity) {

		T saved = null;

		getInstance().getTransaction().begin();
		saved = getInstance().merge(entity);
		getInstance().getTransaction().commit();
		
		return saved;
	}

	@Override
	public T update(T entity) {
		return save(entity);		
	}
	
	@Override
	public void delete(T entity) {
		getInstance().getTransaction().begin();
		getInstance().remove(entity);
		getInstance().getTransaction().commit();

	}

	@Override
	public T findById(Class<T> classe, ID id) {

		try {
			return getInstance().find(classe, id);
		} catch (NoResultException e) {
			return null;
		}

	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> findAll(Class<T> classe) {

		return getInstance().createQuery(
				"select o from " + classe.getSimpleName() + " o")
				.getResultList();
	}

	
	private EntityManager getEntityManager() {
		if(factory == null){
			try {
				//TODO rever forma de instanciar EntityManagerFactor
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return factory.createEntityManager();
	}
	
	public synchronized EntityManager getInstance(){
		if(em == null){
			em = getEntityManager();
		}
		
		return em;
	}	
}